from typing import Any, Optional, Dict
from dataclasses import dataclass
from flask import jsonify


@dataclass
class ApiResponse:
    success: bool
    data: Optional[Any] = None
    message: Optional[str] = None
    error: Optional[str] = None
    code: int = 200

    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        result = {
            'success': self.success
        }

        if self.data is not None:
            result['data'] = self.data

        if self.message is not None:
            result['message'] = self.message

        if self.error is not None:
            result['error'] = self.error

        return result

    def to_json_response(self):
        """转换为Flask JSON响应"""
        return jsonify(self.to_dict()), self.code


class ApiResponseBuilder:
    """API响应构建器"""

    @staticmethod
    def success(data: Any = None, message: str = None, code: int = 200) -> ApiResponse:
        """构建成功响应"""
        return ApiResponse(
            success=True,
            data=data,
            message=message,
            code=code
        )

    @staticmethod
    def error(error: str, code: int = 400, data: Any = None) -> ApiResponse:
        """构建错误响应"""
        return ApiResponse(
            success=False,
            error=error,
            data=data,
            code=code
        )

    @staticmethod
    def not_found(resource: str = "资源") -> ApiResponse:
        """构建404响应"""
        return ApiResponse(
            success=False,
            error=f"{resource}不存在",
            code=404
        )

    @staticmethod
    def internal_error(error: str = "服务器内部错误") -> ApiResponse:
        """构建500响应"""
        return ApiResponse(
            success=False,
            error=error,
            code=500
        )

    @staticmethod
    def validation_error(error: str) -> ApiResponse:
        """构建参数验证错误响应"""
        return ApiResponse(
            success=False,
            error=f"参数验证失败: {error}",
            code=400
        )